<template>
  <WorkspaceLayout :left-drawer="showDrawer" background>

    <template v-slot:header-title>
      <span>个人空间</span>
    </template>

    <template v-slot:page>
      <q-carousel
          v-model="workbenchSlide"
          transition-prev="slide-right"
          transition-next="slide-left"
          animated
          control-color="primary"
          keep-alive
          style="height: 100vh;background-color: rgba(0,0,0,0)"
      >
        <q-carousel-slide
            v-for="item in workbenches"
            class="q-pa-none"
            :name="item.id"
            :key="item.id"
            style="height: 100vh;background-color: rgba(0,0,0,0)"
        >
          <the-widget-grid-panel :id="item.id"></the-widget-grid-panel>
        </q-carousel-slide>
        <!--        <q-carousel-slide name="style" class="column no-wrap flex-center">-->
        <!--          <q-icon name="style" color="primary" size="56px" />-->
        <!--          <the-widget-grid-panel ></the-widget-grid-panel>-->
        <!--        </q-carousel-slide>-->
      </q-carousel>
    </template>

    <!--用户侧边栏-->
    <template v-slot:left-drawer>
      <user-panel></user-panel>
    </template>

    <!--时间线日志-->
    <template v-if="modules.timelinePanel">
      <q-drawer v-if="modules.timelinePanel" show-if-above v-model="right" side="right" bordered>
        <the-timeline-panel></the-timeline-panel>
      </q-drawer>
    </template>

    <template v-slot:append>
      <the-background-management v-model:show="backgroundDialogShow"></the-background-management>

      <TheWidgetManagement
          ref="widgetManagement"
          v-model:show="appManagementDialogShow">
      </TheWidgetManagement>

      <the-feedback-management v-model:show="feedbackDialogShow"></the-feedback-management>

      <the-quick-build-panel v-model:show="quickBuildPanelShow"></the-quick-build-panel>

      <q-page-sticky position="bottom" :offset="[12,12]" class="z-fab">
        <template v-if="workbenches.length > 1 && !$store.getters.isShare">
          <div
              class="q-ma-sm inline-block"
              v-for="item in workbenches"
              :key="item.id"
              @click="switchWorkbench(item)"
          >
            <q-btn
                :outline="$store.state.currentWorkbenchId !== item.id"
                color="primary"
                rounded
                :icon="item.icon || 'web'"
            >{{ item.name }}
            </q-btn>
            <q-popup-proxy context-menu>
              <q-list style="min-width: 100px">
                <q-item clickable v-close-popup @click.stop="editPanel(item)">
                  <q-item-section>编辑应用</q-item-section>
                </q-item>
                <q-separator/>
                <q-item clickable v-close-popup @click.stop="removePanel(item)">
                  <q-item-section>删除面板</q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click.stop="sharePanel(item)">
                  <q-item-section>分享面板</q-item-section>
                </q-item>
              </q-list>
            </q-popup-proxy>
          </div>
        </template>
        <template v-if="$store.getters.isShare">
          <q-btn flat color="primary" icon="share">来自 {{ $store.state.sharePanelInfo.userName }} 的分享</q-btn>
          <q-btn class="q-mx-sm" rounded color="grey-10" icon="add"
                 @click="saveSharePanel">
            <span class="q-ml-sm">保存分享面板</span>
          </q-btn>
        </template>
        <template v-if="!$store.getters.isShare">
          <q-btn class="q-mx-sm" rounded color="grey-10" icon="add"
                 @click="appManagementDialogShow=true">
            <span class="q-ml-sm">添加组件</span>
            <q-tooltip anchor="top middle" self="bottom middle" content-class="bg-primary" :offset="[10, 10]">
              <span>快捷键：J</span>
            </q-tooltip>
          </q-btn>
          <q-btn class="q-mx-sm" rounded color="grey-10" icon="wallpaper"
                 @click="backgroundDialogShow=true">
            <span class="q-ml-sm">设置背景</span>
            <q-tooltip anchor="top middle" self="bottom middle" content-class="bg-primary" :offset="[10, 10]">
              <span>点击展开背景图片管理面板</span>
            </q-tooltip>
          </q-btn>
          <q-btn v-if="$store.state.userInfo.role === 99" class="q-mx-sm" rounded color="grey-10" icon="account_box"
                 @click="handlerLogin">
            <span class="q-ml-sm">注册/登录</span>
            <q-tooltip anchor="top middle" self="bottom middle" content-class="bg-primary" :offset="[10, 10]">
              <span>保存个人配置，便于多终端同步。</span>
            </q-tooltip>
          </q-btn>
        </template>
      </q-page-sticky>
      <q-page-sticky position="bottom-left">
        <q-btn
            flat
            type="a"
            color="white"
            href="https://beian.miit.gov.cn/#/Integrated/index">京ICP备2021027747号
        </q-btn>
      </q-page-sticky>
      <!-- 操作按钮 -->
      <q-page-sticky
          position="bottom-right" :offset="[12,12]" class="z-fab">
        <q-fab
            v-if="$store.state.userInfo.role !== 99"
            v-model="fabShow"
            vertical-actions-align="left"
            color="primary"
            glossy
            icon="keyboard_arrow_up"
            direction="left"
        >
          <q-fab-action label-position="right" color="accent" @click="showFeedbackDialog" icon="feedback" label="留言反馈"/>
          <q-fab-action label-position="right" color="green" @click="goMsg" icon="message" label="通知配置"/>
          <q-fab-action label-position="right" color="green" @click="createNewPanel" icon="add" label="添加新面板"/>
          <q-fab-action label-position="right" color="grey" @click="logout" icon="logout" label="退出"/>
        </q-fab>
      </q-page-sticky>
      <q-page-sticky position="left" v-if="!$store.getters.isShare">
        <q-btn
            round flat color="primary" size="35px"
            icon="keyboard_arrow_left"
            @click="switchWorkbench('left')"
        />
      </q-page-sticky>
      <q-page-sticky position="right" v-if="!$store.getters.isShare">
        <q-btn
            round flat color="primary" size="35px"
            icon="keyboard_arrow_right"
            @click="switchWorkbench('right')"
        />
      </q-page-sticky>
    </template>
    <!--时间线日志-->
    <template v-if="modules.timelinePanel">
      <q-drawer v-if="modules.timelinePanel" show-if-above v-model="right" side="right" bordered>
        <the-timeline-panel></the-timeline-panel>
      </q-drawer>
    </template>
  </WorkspaceLayout>
</template>

<script>

import { defineComponent, defineAsyncComponent } from 'vue'
import WorkspaceLayout from 'src/layouts/WorkspaceLayout.vue'
import TheWidgetGridPanel from 'src/pages/workbench/TheWidgetGridPanel.vue'
import TheTimelinePanel from 'src/pages/workbench/TheTimelinePanel.vue'
import TheBackgroundManagement from 'src/pages/workbench/TheBackgroundManagement.vue'
import UserPanel from 'src/pages/user/UserPanel.vue'
import TheFeedbackManagement from 'src/pages/workbench/TheFeedbackManagement.vue'
import TheQuickBuildPanel from './workbench/TheQuickBuildPanel.vue'
import iUser from '../api/user'
import emitter from 'tiny-emitter/instance'

export default defineComponent({
  name: 'Workspace',
  components: {
    TheWidgetGridPanel,
    TheTimelinePanel,
    WorkspaceLayout,
    UserPanel,
    TheBackgroundManagement,
    TheQuickBuildPanel,
    TheFeedbackManagement,
    TheWidgetManagement: defineAsyncComponent(() => import('src/pages/workbench/TheWidgetManagement.vue'))
  },
  data () {
    return {
      modules: {
        header: false,
        timelinePanel: false,
        taskPanel: true
      },
      backgroundDialogShow: false,
      feedbackDialogShow: false,
      appManagementDialogShow: false,
      showDrawer: false,
      quickBuildPanelShow: false,
      fabShow: false,
      isDevelopment: process.env.NODE_ENV === 'development',
      workbenchSlide: 'main',
      isSwitching: false
    }
  },
  provide () {
    this.workbenchEventBus = emitter
    return {
      workbenchEventBus: this.workbenchEventBus
    }
  },
  computed: {
    workbenches () {
      if (this.$route.query.shareId) {
        return [
          {
            id: this.$route.query.shareId,
            name: '',
            icon: 'share'
          }
        ]
      }
      return [
        {
          id: 'main',
          name: '',
          icon: 'home'
        },
        ...this.$store.state.workbenches
      ]
    },
    currentWorkbenchIndex () {
      return this.workbenches.findIndex(e => e.id === this.$store.state.currentWorkbenchId)
    }
  },
  watch: {
    '$store.state.widget.options' (newValue) {
      this.quickBuildPanelShow = !newValue.initialized
    },
    '$store.state.currentWorkbenchId' () {
      this.workbenchSlide = this.$store.state.currentWorkbenchId
    }
  },
  async mounted () {
    this.init()
    // 初始化用户信息 - 从云端存储加载数据
    await this.$store.dispatch('initUserInfo')
    if (this.$route.query.id) {
      this.$store.commit('setCurrentPanel', {
        id: this.$route.query.id
      })
    } else if (this.$route.query.shareId) {
      this.$store.commit('setCurrentPanel', {
        shareId: this.$route.query.shareId
      })
    }
    await this.$store.dispatch('storeLoad')
    // 申请权限  - 通知
    Notification.requestPermission().then(e => {
      console.info('通知权限请求结果', e)
    })
  },
  beforeUnmount () {
    this.destroy()
  },
  methods: {
    init () {
      window.addEventListener('keydown', this.onKeydown)
      this.workbenchEventBus.on('keydown', event => {
        if (event.code === 'ArrowRight') {
          this.switchWorkbench('right')
        }
        if (event.code === 'ArrowLeft') {
          this.switchWorkbench('left')
        }
      })
    },
    destroy () {
      window.removeEventListener('keydown', this.onKeydown)
    },
    onKeydown (event) {
      // 排除富文本编辑器按键事件
      const contentEditable = !!event.target.getAttribute('contenteditable')
      if (contentEditable) return
      // 排除各种表单元素按键事件
      const formTagNames = [
        'INPUT',
        'TEXTAREA',
        'SELECT',
        'OPTIONS',
        'FORM',
        'BUTTON'
      ]
      const formTagMatchReg = new RegExp(formTagNames.join('|'))
      if (formTagMatchReg.test(event.target.tagName)) {
        return
      }
      if (event.code === 'KeyJ') {
        if (!this.appManagementDialogShow) {
          this.appManagementDialogShow = true
        } else {
          if (this.$refs.widgetManagement) {
            this.$refs.widgetManagement.nextWidget()
          }
        }
      }
      this.workbenchEventBus.emit('keydown', event)
    },
    async handlerLogin () {
      await this.$router.push({ name: 'Login' })
    },
    async handlerSetting () {
      const { href } = this.$router.resolve({ path: '/setting' })
      window.open(href, '_blank')
    },
    showFeedbackDialog () {
      this.feedbackDialogShow = true
    },
    async logout () {
      await this.$store.dispatch('logout')
      location.reload()
    },
    goMsg () {
      this.$router.push({ name: 'Message' })
    },
    createNewPanel () {
      const isShare = this.$store.state.shareId
      this.$q.dialog({
        title: isShare ? '保存面板' : '创建新面板',
        message: '输入新工作面板的名称?',
        prompt: {
          model: '',
          type: 'text'
        },
        cancel: true,
        persistent: true
      }).onOk(async name => {
        await this.$store.dispatch('createPanel', name)
        this.initSlideSwitch()
        this.$q.notify({
          icon: 'announcement',
          message: '保存到个人面板成功！',
          color: 'info',
          position: 'top',
          timeout: 1500
        })
      })
    },
    initSlideSwitch () {
      this.switchWorkbench({
        id: this.$store.state.currentWorkbenchId
      })
    },
    async switchWorkbench (workbench) {
      if (this.isSwitching) return
      this.isSwitching = true
      if (workbench === 'left') {
        let nextIndex = this.currentWorkbenchIndex - 1
        if (nextIndex < 0) nextIndex = this.workbenches.length - 1
        workbench = this.workbenches[nextIndex]
      }
      if (workbench === 'right') {
        let nextIndex = this.currentWorkbenchIndex + 1
        if (nextIndex >= this.workbenches.length) nextIndex = 0
        workbench = this.workbenches[nextIndex]
      }
      if (!workbench) return
      try {
        await this.$router.push({
          name: 'Workspace',
          query: {
            id: workbench.id
          }
        })
        await this.$store.dispatch('switchWorkbench', workbench.id)
      } finally {
        this.isSwitching = false
      }
    },
    editPanel (item) {
      const workbench = { ...item }
      this.$q.dialog({
        title: '编辑面板',
        message: '输入新工作面板的名称?',
        prompt: {
          model: workbench.name,
          type: 'text'
        },
        cancel: true,
        persistent: true
      }).onOk(name => {
        workbench.name = name
        this.$store.dispatch('updateWorkbench', workbench)
      })
    },
    removePanel (item) {
      this.$q.dialog({
        title: '删除面板确认',
        message: `是否确认要删除 ${item.name} 面板（不可撤销）?`,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$store.dispatch('deletePanel', item.id)
        this.initSlideSwitch()
      })
    },
    sharePanel (item) {
      this.$q.dialog({
        title: '生成分享链接',
        message: `是否创建分享链接来分享 ${item.name} 面板?`,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        const { id } = await iUser.createSharePanel({
          id: item.id
        })
        this.$q.dialog({
          title: '分享链接生成成功',
          message: `${location.origin}/panel?shareId=${id}`,
          cancel: true,
          persistent: true
        })
      })
    },
    saveSharePanel () {
      this.createNewPanel()
    }
  }
})
</script>

<style lang="scss">

:root::-webkit-scrollbar {
  width: 0;
  background-color: #F5F5F5;
}

</style>
